#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

int main(int argc,char * argv[])
{
  if(argc != 3)
  {
    printf("Usage : ./client IP Port\n");
    return 1;
  }

  sockaddr_in peer ;
  peer.sin_family = AF_INET;
  peer.sin_addr.s_addr = inet_addr(argv[1]);
  peer.sin_port = htons(atoi(argv[2]));

  int fd = socket(AF_INET,SOCK_STREAM,0);
  if(fd < 0)
  {
    perror("socket");
    return 1;
  }

  int ret = connect(fd,(sockaddr *)&peer,sizeof(peer));

  if(ret < 0)
  {
    perror("connect");
    return 1;
  }

  char buf[1024] = {0};
  while(1)
  {
    //从标准输入读取数据
    ssize_t read_size = read(0,buf,sizeof(buf));
    if(read_size < 0)
    {
      perror("read");
      return 1;
    }
    buf[read_size] = '\0';

    //向服务器发送数据
    write(fd,buf,strlen(buf));

    //开始接收服务器的响应
    char read_buf[1024] = {0};
    read_size = read(fd,read_buf,sizeof(read_buf));
    if(read_size < 0)
    {
      perror("read");
      continue;
    }
    if(read_size == 0)
    {
      printf("server close\n");
      return 0;
    }
    read_buf[read_size] = '\0';
    printf("server echo # %s",read_buf);

  }

}
